[% setvar title Pattern matching on perl values %]
<div id="archive-notice">
    <h3>This file is part of the Perl 6 Archive</h3>
    <p>To see what is currently happening visit <a href="http://www.perl6.org/">http://www.perl6.org/</a></p>
</div>
<div class='pod'>
<a name='TITLE'></a><h1>TITLE</h1>
<p>Pattern matching on perl values</p>
<a name='VERSION'></a><h1>VERSION</h1>
<pre>  Maintainer: Steve Fink &lt;<a href='mailto:steve@fink.com'>steve@fink.com</a>&gt;
  Date: 19 Sep 2000
  Mailing List: <a href='mailto:perl6-language@perl.org'>perl6-language@perl.org</a>
  Number: 261
  Version: 1
  Status: Developing</pre>
<a name='ABSTRACT'></a><h1>ABSTRACT</h1>
<p>A pattern matching primitive that operates on perl values would allow
sophisticated data slicing and dicing to be specified concisely.</p>
<a name='DESCRIPTION'></a><h1>DESCRIPTION</h1>
<a name='EXAMPLES'></a><h2>EXAMPLES</h2>
<p>Best illustrated by examples:</p>
<pre>  # Nearly identical to current behavior
  my ($a, $b, $c) = @_;

  # Changes current behavior. $b is set only if ! defined $_[0]
  my (undef, $b) = @_;

  # Nearly equivalent to the present my (undef, $b) = @_
  my (?, $b) = @_

  # Equiv to my $name = $hashref-&gt;{name}; my @kids = @{$hashref-&gt;{children}}
  my { 'name' =&gt; $name, children =&gt; [ @kids ] } = $hashref;

  # Operationally equiv to my $b = $_[1]-&gt;{food};
  # my ($a) = grep { $_[1]-&gt;{$_} eq 'fish' } keys %{$_[1]}
  # even if $_[1]-&gt;{food} eq 'fish'
  my (undef, { $a =&gt; 'fish', food =&gt; $b }) = @_;

  # $a is an arbitrarily chosen key of %$h, and $b is its value.
  # $c is a key whose value is a hash ref containing 'needle' as a key.
  # In this and all other examples, if any pattern match fails,
  # the whole match fails and does not assign any variables.
  my { $a =&gt; $b, $c =&gt; { needle =&gt; ? } } = $h;

  # If you are not declaring variables, 'match' performs the same operation
  # for existing variables. This one sets $a to $foo[0] unless @foo==0.
  match ($a) = @foo;

  # Constants can be matched against too.
  match { 'Joe' =&gt; ? } = $h or die &quot;Hash does not contain Joe&quot;;

  # Equiv to scalar(grep { $_ == 1 } @list)
  match (..., 1, ...) = @list;

  # Pretty close to ($idx) = grep { $_[$_] == 1 } @_; $b = $_[$idx+1];
  match (..., 1, $b) = @_;

  # It gets worse! This gives the value associated with a key matching the
  # regular expression a*b:
  match { /a*b/ =&gt; $value } = \%h;

  # And if you want to know what the key was:
  match { $key = /a*b/ =&gt; $value } = \%h;

  # What if you want to grab out the index? This is like
  # ($i) = grep { $list[$_] =~ /foo/ } 0..$#list
  match ( $i =&gt; /foo/ ) = @list;

  # If you don't want to require the trailing parts of the pattern to match:
  match ($a, 1, $b, :optional $c, 2, $d) = @_;

  # Equivalent to my Dog $puppy = $h-&gt;{puppy}, whatever my Dog $puppy
  # is chosen to mean.
  my { 'puppy' =&gt; Dog $puppy } = $h;

  # Equiv to my Dog $temp = $h-&gt;{puppy}; $puppy = $temp;
  # (Performs whatever assertion checking my Dog $var would normally do.)
  match { 'puppy' =&gt; Dog $puppy } = $h;

  # Depending on the final meaning of my Dog $puppy, this may search for
  # something satisifying the my Dog $puppy assertions. So it would be
  # similar to
  #  while (($k,$v) = each %$h) {
  #     ($slot,$puppy) = ($k,$v), last if UNIVERSAL::isa($v, 'Dog');
  #  }
  my { $slot =&gt; Dog $puppy } = $h;</pre>
<a name='DETAILS'></a><h2>DETAILS</h2>
<p>The syntax is</p>
<pre> MATCH-EXPR : (my|match) PATTERN = EXPR
 PATTERN : '{' HASH-PATTERN-LIST '}'
         | '(' LIST-PATTERN-LIST ')'
         | '[' LIST-PATTERN-LIST ']'
         | 'undef'
         | '?'
         | '...'
         | VARIABLE
         | CONSTANT
         | REGEX
         | VARIABLE '=' PATTERN
 HASH-PATTERN : PATTERN '=&gt;' PATTERN
 HASH-PATTERN-LIST : /* empty */
                   | HASH-PATTERN ',' HASH_PATTERN-LIST
                   | ':optional' HASH-PATTERN ',' HASH_PATTERN-LIST
 LIST-PATTERN-LIST : /* empty */
              | LIST-PATTERN ',' LIST-PATTERN-LIST
              | ':optional' LIST-PATTERN ',' LIST-PATTERN-LIST
 LIST-PATTERN : PATTERN
              | PATTERN =&gt; PATTERN</pre>
<p>Both <code>my</code> and <code>match</code> return the number of variables successfully
matched. The behavior of</p>
<pre> my $a = 1 if cond();</pre>
<p>is changed to mean</p>
<pre> my $a;
 $a = 1 if cond();</pre>
<p>So that you can easily test the success of pattern matching:</p>
<pre> my { $a =&gt; 'Bob' } = \%h
        or warn &quot;Bob ain't here!&quot;; </pre>
<p>For the case of <code>match (...)</code>, each PATTERN is matched against the
corresponding element of the right hand side (rhs). If the rhs runs
out of elements, the whole match fails and the return value is
undefined. For example, <code>match (@a, $b) = @_</code> will always leave both
@a and $b unaffected because @a will have eaten all of @_.</p>
<p>For the case of <code>match {...}</code>, the rhs must be a reference to a hash.
Conceptually, each (key,value) pair is matched against all of the
HASH-PATTERN key and value pattern pairs in turn. If multiple
(key,value) pairs match the same PATTERN=&gt;PATTERN pair, which ones are
matched to which is undefined (multiple patterns may be considered as
matching the same (key,value) pair, and vice versa.)</p>
<p><code>undef</code> now means that the matching value MUST be undefined, rather
than serving as a &quot;don't care&quot; placeholder as it does now in some
contexts. The placeholder function is taken over by <code>?</code>. <code>...</code> is a
variable-length placeholder matching zero or more list elements.</p>
<p>When using <code>:optional</code> and no variables are matched, the special
value &quot;0 but true&quot; is returned.</p>
<a name='DISCUSSION'></a><h2>DISCUSSION</h2>
<p>It might be preferable to just die() on a failed match, although that
would make it harder to do some of the grep replacements.</p>
<p>Forcing patterns to match unique list or hash elements would make this
more powerful, but would make it harder to implement, slower, and
possibly more confusing.</p>
<p>It would be very useful to match against a hash (not just a hash
reference). Suggestions for syntax? This would allow</p>
<pre> sub new {
    my ( __PACKAGE__ $self,
         %{ PeerAddr =&gt; $addr, :optional LocalAddr =&gt; $localaddr }
       ) = @_;</pre>
<p>It might be better to leave <code>my</code> unchanged and either only provide
<code>match</code> or provide another keyword for both matching and creating the
lexical variables. If that were done, then we might also consider using
<code>EXPR =~ PATTERN</code> rather than <code>PATTERN = EXPR</code>.</p>
<a name='MIGRATION'></a><h1>MIGRATION</h1>
<pre> my (undef, $a, undef) = @_;</pre>
<p>would be rewritten</p>
<pre> my (:optional ?, $a, ?) = @_;</pre>
<p>In other words, all <code>undef</code>'s in <code>my()</code> lists would be changed to
<code>?</code>, and <code>:optional</code> would be placed at the beginning of the list.</p>
<p>This is still a buggy migration, because pattern matching returns the
number of variables assigned, while perl5 returns the rhs list padded
to the number of elements on the lhs, or something like that. Avoiding
the use of <code>my</code> for pattern matching would solve this, as would
making a <code>perl5_my</code> operator.</p>
<a name='IMPLEMENTATION'></a><h1>IMPLEMENTATION</h1>
<p>Fairly straightforward. I long ago prototyped a simplified version of
this in perl5, though it required you to quote the pattern and would
only assign to global variables. In order to be useful, though, this
needs to be implemented in C.</p>
<a name='REFERENCES'></a><h1>REFERENCES</h1>
<p>RFC 22: Control flow: Builtin switch statement</p>
<p>This feels similar to Damian Conway's <code>switch</code> operator, and some
unification might be useful. I doubt the fully generalized union would
be as useful as two specialized primitives.</p>
<p>RFC 156: Replace first match function (<code>?...?</code>) with a flag to the
match command</p>
<p>This is necessary to avoid parsing ambiguity with the ? placeholder.</p>
<p>RFC 164: Replace =~, !~, m//, s///, and tr// with match(), subst(),
and trade()</p>
<p>This also uses the <code>match</code> keyword, though either RFC could easily
switch to another.</p>
<p>RFC 170: Generalize =~ to a special &quot;apply-to&quot; assignment operator</p>
<p>This would provide the EXPR =~ match PATTERN syntax, similar to
EXPR =~ PATTERN above.</p>
<p>RFC 218: <code>my Dog $spot</code> is just an assertion</p>
<p>I've been assuming this or something similar in the semantics described.</p>
</div>
